package com.java.module.user.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.java.common.lang.domain.entity.User;
import com.java.common.utils.AliyunDypnsConfig;
import com.java.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class AliyunMobileAuthService {

    private final AliyunDypnsConfig config;

    /**
     * 通过accessToken获取手机号
     * @param accessToken Uniapp一键登录获取的token
     * @return 手机号
     */
    public String getMobileNumber(String accessToken) throws Exception {
        // 1. 构建请求体
        Map<String, String> body = new HashMap<>();
        body.put("token", accessToken);
        body.put("type", "1"); // 1表示一键登录

        // 2. 创建HTTP请求
        HttpPost httpPost = new HttpPost(config.getVerifyUrl());
        httpPost.setHeader("Authorization", "APPCODE " + config.getAppCode());
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(JSON.toJSONString(body), "UTF-8"));

        // 3. 发送请求并解析响应
        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpPost)) {

            String responseBody = EntityUtils.toString(response.getEntity());
            return parseResponse(responseBody);
        }
    }

    /**
     * 解析阿里云响应
     */
    private String parseResponse(String responseBody) throws Exception {
        JSONObject json = JSON.parseObject(responseBody);

        if (!"OK".equals(json.getString("Code"))) {
            throw new RuntimeException("阿里云认证失败: " + json.getString("Message"));
        }

        JSONObject data = json.getJSONObject("Data");
        if (data == null) {
            throw new RuntimeException("响应数据异常");
        }

        String mobile = data.getString("Mobile");
        if (StringUtils.isEmpty(mobile)) {
            throw new RuntimeException("未获取到手机号");
        }

        return mobile;
    }

    /**
     * 获取手机号并创建登录Token（完整业务方法）
     */
    public String verifyAndLogin(String accessToken) {
        try {
            // 1. 获取手机号
            String mobile = this.getMobileNumber(accessToken);



            return mobile;
        } catch (Exception e) {

            return e.getMessage();
        }
    }


}
